package com.rong.iconhero.controller;

import com.rong.iconhero.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 周厚荣
 * @date 2025/4/28 16:42
 */
@RestController
@Slf4j
@RequestMapping("/info")
public class InfoController {
    /*
     * 获取网址中数据，标题、描述内容、图标
     * */
    @GetMapping
    public ResponseVO getWebsiteInfo(@RequestParam String url) throws IOException {
        /*使用Jsoup库的connect方法连接到指定的URL，并使用get方法获取网页的内容。它返回一个Document对象，表示整个HTML文档。*/
        Document doc = Jsoup.connect(url).get();

        /*获取网站元数据*/
        String title = doc.title();
        Element descriptionTag = doc.select("meta[name=description]").first();
        String description = descriptionTag != null ? descriptionTag.attr("content") : "";
        Element iconTag = doc.select("link[rel=icon], link[rel=shortcut icon]").first();
        String iconLink = iconTag != null ? iconTag.attr("href") : "";

        /*返回前端*/
        Map<String, String> map = new HashMap<>();
        map.put("title", title);
        map.put("description", description);
        map.put("iconLink", iconLink);
        log.warn(map.toString());
        return ResponseVO.getSuccessResponseVO(map);
    }
}
